package com.eco.fanliapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.dao.AppGeneralfeeschemeMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.BigDecimalUtils;
import com.eco.fanliapp.utils.ComputeUtil;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @date 2020-03-12
 */
@Slf4j
@Service
public class PddOrderInfoServiceImpl implements IPddOrderInfoService {
    @Autowired
    private IPddOrderDetailService iPddOrderDetailService;
    @Autowired
    private IPddUserOrderService pddUserOrderService;
    @Autowired
    private AppGeneralfeeschemeMapper appGeneralfeeschemeMapper;
    @Autowired
    private ICommissionFreezeService commissionFreezeService;
    @Autowired
    private IAppNewsLogService iAppNewsLogService;
    @Autowired
    private IAppUserService appUserService;
	@Autowired
	private ISyUserMoneyLogService syUserMoneyLogService;
    @Override
    public void handlePddOrder(List<PddOrderDetail> orderList) {
        if(orderList != null && orderList.size()>0){
            for (PddOrderDetail pddOrderDetail:orderList) {
                if(pddOrderDetail != null && pddOrderDetail.getOrderSn() != null && !pddOrderDetail.getOrderSn().isEmpty()){
                    try {
                        //订单详情
                        Long spareMoney = 0L;
                                log.info("拼多多****用户Id{},{}订单号",pddOrderDetail.getCustomParameters(),pddOrderDetail.getOrderSn());
                        iPddOrderDetailService.saveOrUpdate(pddOrderDetail);
                        //处理分佣
                        Long commission = handlePddCommission(pddOrderDetail.getCustomParameters(), pddOrderDetail.getOrderSn(), pddOrderDetail.getPromotionAmount(),pddOrderDetail.getOrderStatus());
                        spareMoney = commission + pddOrderDetail.getGoodsPrice()*pddOrderDetail.getGoodsQuantity() - pddOrderDetail.getOrderAmount();
                        //处理order
                        handlePddUserOrder(pddOrderDetail.getCustomParameters(),pddOrderDetail.getOrderSn(),pddOrderDetail.getOrderStatus(),pddOrderDetail.getOrderVerifyTime(),commission,spareMoney,pddOrderDetail.getGoodsName());
                    }catch (Exception e){
                        log.info("拼多多订单存储错误***用户id{}订单编号{}",pddOrderDetail.getCustomParameters(),pddOrderDetail.getOrderSn());
                    }
                }
            }
        }
    }

//    @Override
//    public void testPddOrder(String orderSn) {
//        orderSn = "200321-441001247932663";
//        Long spareMoney = 0L;
//        QueryWrapper<PddOrderDetail> detail = new QueryWrapper<>();
//        detail.eq("order_sn",orderSn);
//        PddOrderDetail pddOrderDetail = iPddOrderDetailService.getOne(detail);
//        Long commission = handlePddCommission(pddOrderDetail.getCustomParameters(), pddOrderDetail.getOrderSn(), pddOrderDetail.getPromotionAmount(),pddOrderDetail.getOrderStatus());
//        spareMoney = commission + pddOrderDetail.getGoodsPrice()*pddOrderDetail.getGoodsQuantity() - pddOrderDetail.getOrderAmount();
//        //处理order
//        handlePddUserOrder(pddOrderDetail.getCustomParameters(),pddOrderDetail.getOrderSn(),pddOrderDetail.getOrderStatus(),pddOrderDetail.getOrderVerifyTime(),commission,spareMoney,pddOrderDetail.getGoodsName());
//
//    }

    /**
     * 计算拼多多用户补贴
     * @param customParameters
     * @param orderSn
     * @param promotionAmount
     * @return
     */
    public Long handlePddCommission(String customParameters,String orderSn,Long promotionAmount,int orderStatus ){
        log.info("计算拼多多用户补贴,用户id：{};订单号：{};联盟佣金：{};订单的状态：{}",customParameters,orderSn,promotionAmount,orderStatus);
        Long commission = 0L;
        try {
            if(StringUtils.isNull(customParameters)){
                return commission;
            }
            if(orderStatus == -1 || orderStatus == 4 || orderStatus == 8){
                return commission;
            }
            //判断order是否存在
            PddUserOrder pddUserOrder = pddUserOrderService.selectByOrderSn(orderSn);
            if(pddUserOrder == null){
                //1.获取人所属公司;2.获取返佣的信息
                AppGeneralFeeScheme generalFeeScheme = appGeneralfeeschemeMapper.selectGeneralFeeScheme(Long.valueOf(customParameters),1);

                //联盟佣金(分/100 = 元)
                double promotion = promotionAmount.doubleValue() / 100;
                log.info("计算拼多多用户补贴,联盟佣金：{}，单位：（元）",promotion);
				//计算补贴金额
				Integer orderScale = null;
				if (generalFeeScheme.getOnepay() >= promotion) {
					orderScale = generalFeeScheme.getOnepayScale();
				} else if (generalFeeScheme.getTwopay() >= promotion) {
					orderScale = generalFeeScheme.getTwopayScale();
				} else if (generalFeeScheme.getThirdpay() >= promotion) {
					orderScale = generalFeeScheme.getThirdpayScale();
				} else if (generalFeeScheme.getForpay() >= promotion) {
					orderScale = generalFeeScheme.getForpayScale();
				} else if (generalFeeScheme.getFivepay() >= promotion) {
					orderScale = generalFeeScheme.getFivepayScale();
				} else if (generalFeeScheme.getSixpay() >= promotion) {
					orderScale = generalFeeScheme.getSixpayScale();
				} else if (generalFeeScheme.getSevenpay() >= promotion) {
					orderScale = generalFeeScheme.getSevenpayScale();
				}

                log.info("计算拼多多用户补贴,计算的佣金比率：{}",orderScale);
                //补贴价格
                commission = BigDecimalUtils.FanliMoney(String.valueOf(orderScale), new BigDecimal(promotionAmount)).longValue();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return commission;
        }
        log.info("计算拼多多用户补贴,返回的佣金：{}",commission);
        return commission;
    }

    /**
     * 计算拼多多用户补贴延迟天数
     * @param orderVerifyTime
     * @return
     */
    public Long handleDelayTime(Long orderVerifyTime){
        //获取设置的延迟天数
        CommissionFreeze commissionFreeze = commissionFreezeService.selectByPrimaryKey(2, 1);
        Integer delaydays = commissionFreeze.getDelaydays();

        return getDateTime(orderVerifyTime,delaydays);
    }

    /**
     * 处理pdd订单表（1.分佣；2.延迟天数；3.状态的处理；4.防止重复处理）
     * @param customParameters
     * @param orderSn
     * @param orderStatus
     * @param orderReceiveTime
     * @param commission
     */
    public void handlePddUserOrder(String customParameters,String orderSn,int orderStatus ,Long orderReceiveTime,Long commission,Long spareMoney,String goodsName){
        log.info("处理pdd订单表,用户id：{}；订单编号：{}；订单状态：{}；延迟时间：{}；用户补贴：{}；商品标题：{}",customParameters,orderSn,orderStatus,commission,goodsName);
		if(StringUtils.isNull(customParameters)){
			return;
		}
        //判断order表是否已存在，有就新增，没有就更新
        Long commissionMes = 0L;
        PddUserOrder pddUserOrder = pddUserOrderService.selectByOrderSn(orderSn);
        PddUserOrder userOrder = new PddUserOrder();
        if(pddUserOrder == null){
            commissionMes = commission;
            userOrder.setUserId(Long.valueOf(customParameters));
            userOrder.setOrderSn(orderSn);
            userOrder.setCommission(commission);
            userOrder.setOrderStatus(orderStatus);
            userOrder.setSpareMoney(spareMoney);
        }else{
            //状态相同不处理
            if(pddUserOrder.getOrderStatus() == orderStatus){
                return;
            }
            //退款订单扣除补贴
            if(pddUserOrder.getOrderSettleStatus() == 2){
                if(orderStatus == -1 || orderStatus == 4 || orderStatus == 8){
                    handleUserBalance(pddUserOrder.getUserId(),pddUserOrder.getCommission());
                }else{
                    return;
                }
            }

            userOrder.setTableId(pddUserOrder.getTableId());
            userOrder.setOrderStatus(orderStatus);
            if(orderStatus == -1 || orderStatus == 4 || orderStatus == 8){
                userOrder.setCommission(0L);
            }
            commissionMes = pddUserOrder.getCommission();
        }
        //计算大额延迟的时间
        if(orderStatus == 2 || orderStatus == 3 || orderStatus == 5){
            Long aLong = handleDelayTime(orderReceiveTime);
            userOrder.setLargeAmountTime(aLong);
        }

        boolean b = pddUserOrderService.saveOrUpdate(userOrder);
        if(b){
            if (orderStatus == 0 || orderStatus == 1) {//已付款
                sendPddMsg(customParameters, NewsEnumLog.NEWS_ORDER_PAY.getNewsType(),commissionMes,goodsName);
            }
            if(orderStatus == -1 || orderStatus == 4 || orderStatus == 8){//无效
                sendPddMsg(customParameters, NewsEnumLog.NEWS_ORDER_FAIL.getNewsType(),commissionMes,goodsName);
            }
            if(orderStatus == 2 || orderStatus == 3 || orderStatus == 5){//结算
                sendPddMsg(customParameters, NewsEnumLog.NEWS_ORDER_SETTLE.getNewsType(),commissionMes,goodsName);
            }
        }
    }

    /**
     * 发送消息
     * @param subUnionId
     * @param newsType
     * @param commission
     */
    public void sendPddMsg(String subUnionId, int newsType,Long commission,String goodsName){
        try {
            //分转元
			double promotion = commission.doubleValue() / 100;
			iAppNewsLogService.newsType(Long.parseLong(subUnionId),newsType,new BigDecimal(promotion), "拼多多",goodsName,String.valueOf(promotion));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理扣钱操作
     * @param userId
     * @param commission
     */
    public void handleUserBalance(Long userId,Long commission){
        //查询这个账户
        log.info("用户id：{}，需要扣除的佣金",userId,commission);
        try {
            AppUser appUser = appUserService.selectAppUserByUserId(userId);
            if(appUser != null){
                double banlance = appUser.getBalance().doubleValue();
                double promotion = commission.doubleValue() / 100;
                //扣钱
                double sub = ComputeUtil.sub(banlance, promotion);
                log.info("扣除金额：{}元",sub);
                //更新
                AppUser user = new AppUser();
                user.setTableId(appUser.getTableId());
                user.setBalance(new BigDecimal(sub));
                appUserService.updateById(user);

                //添加账户变更日志
				syUserMoneyLogService.addSyUserMoneyLog(appUser.getUserId(), new BigDecimal(banlance), new BigDecimal(promotion), "拼多多订单补贴扣除", null, 1);
				log.info("拼多多订单用户id:{},账户变更前余额：{}，账户应扣金额：{},账户变更后余额：{}", appUser.getUserId(), banlance, promotion, sub);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 获取指定时间的时间戳
     * 一天是86400000
     *
     * @param start 天数
     * @return
     */
    public static long getDateTime(Long earningTime, Integer start) {
        Date paramDate = null;
        if (earningTime == null) {
            paramDate = new Date();
        } else {
            paramDate = new Date(earningTime);
        }
        return org.apache.commons.lang3.time.DateUtils.addDays(paramDate, start).getTime();
    }
    public static void main(String[] args) {
        Long promotionAmount = new Long(218);
        double amount = promotionAmount.doubleValue()/100;
        System.out.println(amount);
    }
}
